# 绘制文件夹下所有通道文件
import math
import os
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

from Model import model_customize_station

TITLE = ''
SAMP = 1    #0-原始采样，1-分钟采样，2-小时采样
COPY = 1    #小于等于0的数据是否替换为上一个，值为1开启
SAVE_PATH = "C:\\Users\\11509\\Desktop\\test\\img\\GGd\\"    #图片保存路径

def mySlimping(lines,index):
    #根据slimp值决定数据采样率
    #slimp：0-原始采样，1-分钟采样，2-小时采样
    #分钟和小时采样时，遇到小于等于0的值将替换为上一个值
    content = []
    time = 0
    if SAMP == 1:
        time = 4
    if SAMP == 2:
        time = 240
    if SAMP == 0:      #原始采样
        content = [line.split(',')[index] for line in lines]
    if time != 0:    #分钟采样，4个为一组
        t1 = 0
        n = 0
        i = 0
        for line in lines:
            t2 = float(line.split(',')[index])
            if t2 > 0:
                n += 1
                t1 += t2
            if i % time == 0:
                if n == 0:
                    content.append(0)
                else:
                    content.append(t1/n)
                n = 0
                t1 = 0
            i += 1
    return content

def read_stressFile(stressFile,name,foldPath):
    #sampling：0-原始采样，1-分钟采样，2-小时采样
    file_path = foldPath+"/"+name+"/"+stressFile
    try:
        with open(file_path, 'r') as file:
            # 读取第二行开始所有的内容
            lines = file.readlines()[1:]
            content1 = mySlimping(lines,0)
            content2 = mySlimping(lines, 1)
            return content1,content2
    except FileNotFoundError:
        print(f"文件 {file_path} 未找到.")
        return None
def graphPrinter(group, date, days, label):
    save_path = SAVE_PATH + TITLE + '.png'
    if SAMP == 1:
        slimp = 4
    elif SAMP == 2:
        slimp = 240
    else:
        slimp = 1
    mpl.rcParams['font.size'] = 18
    plt.figure(figsize=(20, 7))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    #plt.title(TITLE)
    plt.ylabel("Mpa")
    x = np.arange(0, len(group[1][1]))
    plt.xlim(0, days * 5760 / slimp)  # 分钟除以4 小时除以240
    plt.xticks(np.arange(0, len(x) + 1, 5760 / slimp), date)
    maxLim = 0
    minLim = math.inf
    prev_value = None
    for i in range(len(group)):
        for j in range(len(group[i])):
            content = []
            for y in group[i][j]:
                y = float(y)
                if y > 0:
                    if y > maxLim:
                        maxLim = y
                    if y < minLim:
                        minLim = y
                    content.append(y)
                    prev_value = y
                elif y <= 0:
                    if COPY == 1:
                        content.append(prev_value)
                    else:
                        content.append(0)
            plt.plot(x, content,label=label[i]+'-'+str(j+1))
    plt.ylim(minLim-0.2, maxLim+0.2)
    plt.yticks(np.arange(math.floor(minLim), maxLim+0.2, 1))
    plt.legend(loc='upper left', bbox_to_anchor=(1, 1),fontsize=10)
    #plt.savefig(save_path)
    plt.show()

def dtestPrinter(folder,station,dates):
    global TITLE
    dates = model_customize_station.complete_date_list(dates)
    if folder:  # 选择了文件夹
        foldNames = model_customize_station.get_file_names(folder)
        group = []         #组数组
        label = []
        date = []
        for name in foldNames:
            if name in station:
                groupt = []
                stressFile = model_customize_station.get_fileByname(name, folder,dates)
                label.append(name)
                groupContent = []
                dateContent = []  # 日期数组
                stressContent1 = []
                stressContent2 = []
                for file in stressFile:
                    dateContent.append(file[file.find("_") + 1:file.find(".")])
                    content1, content2 = read_stressFile(file, name, folder)
                    stressContent1 += content1
                    stressContent2 += content2
                dateContent.append("次日")
                groupContent.append(stressContent1)
                groupContent.append(stressContent2)
                groupt += groupContent
                group.append(groupt)
                date = dateContent
        days = len(date)-1
        graphPrinter(group, date, days, label)